<script setup>
import { ref, inject } from 'vue'
import { FolderOpened } from '@element-plus/icons-vue'

const defaultProps = {
  children: 'children',
  label: 'name'
}
let fileTree = ref([])
const fileContent = inject('fileContent')
const fileName = inject('fileName')

/**
 * @param {}
 * @description 打开文件夹
 */
const onOpenDirectory = async () => {
  const loadingInstance = ElLoading.service({})
  fileContent.value = ''
  try {
    // 获取文件夹
    const handle = await showDirectoryPicker()
    fileTree.value = [await processFileTree(handle)]
  } catch {
    // 拒绝了授权
    ElMessage.info('您取消了操作')
  }
  loadingInstance.close()
}
// 所有的 IO 操作都是异步的， 因为用 async await 递归出所有的文件
const processFileTree = async (handle) => {
  // handle.kind -> directory: 文件夹; file: 文件
  if (handle.kind == 'file') {
    return handle
  }
  handle.children = []
  const iterator = handle.entries()
  for await (const item of iterator) {
    const subItem = await processFileTree(item[1])
    handle.children.push(subItem)
  }

  return handle
}

// 点击时去渲染内容
const handleNodeClick = async (node) => {
  // 渲染 file 的内容
  if (node.kind === 'file') {
    fileName.value = node.name
    const file = await node.getFile()
    const render = new FileReader()
    render.onload = (e) => {
      fileContent.value = e.target.result
    }
    render.readAsText(file, 'utf-8')
  }
}
</script>
<template>
  <div class="container">
    <div class="open-directory" v-show="!fileTree.length">
      <el-button type="primary" :icon="FolderOpened" style="width: 90%" @click="onOpenDirectory">
        打开文件夹
      </el-button>
    </div>
    <div v-show="fileTree.length">
      <el-button
        type="primary"
        size="small"
        :icon="FolderOpened"
        style="width: 100%"
        @click="onOpenDirectory"
      >
        切换文件夹
      </el-button>
      <el-tree :data="fileTree" :props="defaultProps" @node-click="handleNodeClick" />
    </div>
  </div>
</template>
<style scoped>
.container {
  background-color: #f9f9f9;
  height: 100vh;
  overflow-y: auto;
}

.container::-webkit-scrollbar {
  width: 6px;
  height: 9px;
}

.container::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.2);
}

.container::-webkit-scrollbar-track {
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

.open-directory {
  text-align: center;
  margin-top: 25vh;
}
</style>
